<?php

namespace app\model\goods;

use app\base\BaseModel;
use think\facade\Db;
use think\model\concern\SoftDelete;

/**
 * 模型-HotKeywordModel
 * Class HotKeywordModel
 * @package app\model
 */
class HotKeywordModel extends BaseModel
{
    use SoftDelete;
    protected $name = 'hot_keyword';

    /**
     * 范围查询-keyword
     * @param $query
     * @param $keyword
     */
    public function scopeKeyword($query, $keyword)
    {
        if (!empty($keyword)) {
            $query->whereLike('keyword', "%$keyword%");
        }
    }

    public function scopeType($query, $type)
    {
        if (!empty($type)) {
            $query->where('type', $type);
        }
    }

    public function scopeStatus($query, $status)
    {
        if (!empty($status)) {
            $query->where('status', $status);
        }
    }
    /**
     * 获取分页列表
     * @param $map
     * @param $keyword
     * @param $current_page
     * @param $list_rows
     * @param string $field
     * @return array
     */
    public function getPageData($map, $keyword = "", $type, $status, $current_page, $list_rows)
    {
        $dataList = $this
            ->keyword($keyword)
            ->type($type)
            ->status($status)
            ->where($map)
            ->order('id', 'desc')
            ->paginate(['page' => $current_page, 'list_rows' => $list_rows], false);
        $current = $dataList->currentPage();
        $total = $dataList->total();
        $limit = $dataList->listRows();
        $ret = ['total' => $total, 'current' => $current, 'limit' => $limit, 'dataList' => $dataList->items()];
        return $ret;
    }

    /**
     * 增加关键词收拾次数
     * @param $keyword
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function addSearchCount($keyword)
    {
        $key_data = self::where(['keyword' => trim($keyword)])->find();
        if (empty($key_data)) {
            return false;
        }
        $sql = "UPDATE " . self::getTable() . " SET shearch_count = shearch_count + 1 WHERE id = {$key_data['id']}";
        $ret = Db::query($sql);
        if ($ret !== false) {
            return true;
        }
        return false;
    }
}
